package util;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Utility class to construct a JSON error response. E.g. {"status":"error",
 * "message":["error 1", "error 2"]}
 * 
 * @author jaslin.wee.2012, huiwensong.2012, sheryl.tay.2012, mohameds.2012,
 *         huangjm.2012
 * 
 */
public class JsonUtil {

	/**
	 * Regular expression pattern to match Javascript date object enclosed with
	 * double quotes. E.g. "new Date(y, m, d, hrs, min)".
	 */
	private static final String PATTERN_FOR_JAVASCRIPT_DATE_ENCLOSED_WITH_QUOTES = "\\\"(new Date\\([^)]*\\))\\\"";

	/**
	 * Constructs a new JSON error response with the given array of error
	 * messages.
	 * 
	 * @param errors
	 * @return a JSON object
	 */
	public static JSONObject newJsonErrorResponse(JSONArray errors) {
		JSONObject response = new JSONObject();
		response.put("status", "error");
		response.put("message", errors);
		return response;
	}

	/**
	 * Constructs a new JSON error response with the given error message.
	 * 
	 * @param error
	 * @return a JSON object
	 */
	public static JSONObject newJsonErrorResponse(String error) {
		JSONObject response = new JSONObject();
		response.put("status", "error");
		response.put("message", error);
		return response;
	}

	/**
	 * Constructs a new JSON success response.
	 * 
	 * @return a JSON object
	 */
	public static JSONObject newJsonSuccessResponse() {
		JSONObject response = new JSONObject();
		response.put("status", "success");
		return response;
	}

	/**
	 * Removes double quotes around the Javascript date object. The JSON object
	 * treats Javascript Date as if it were a string and encloses it with
	 * quotes. It is necessary to remove those quotes so that the Javascript
	 * Date objects in the JSON can be parsed correctly by the web browser.
	 * 
	 * @param jsonWithJavascriptDate
	 *            a JSON Array
	 * @param indentFactor
	 * @return a JSON string
	 */
	public static String escapeJavascriptDate(JSONArray jsonWithJavascriptDate,
			int indentFactor) {
		return jsonWithJavascriptDate.toString(indentFactor).replaceAll(
				PATTERN_FOR_JAVASCRIPT_DATE_ENCLOSED_WITH_QUOTES, "$1");
	}
	
	public static String getCommaSeperatedErrorMessages(JSONArray errors) {
		return StringUtils.join(errors.toArray(),", ");
	}

}
